from django.utils import timezone
from rest_framework import response
from rest_framework.permissions import IsAdminUser
from rest_framework.response import Response
from rest_framework.views import APIView

from goods.models import GoodsVisitCount
from meiduo_admin.serializers.tongji import GoodsdayviewsSerializer
from users.models import User


class StatisticalTotalconutView(APIView):
    permission_classes = [IsAdminUser]

    def get(self, request):
        counts = User.objects.count()
        date = timezone.now()
        dict = {
            'count': counts,
            'date': date.date()
        }

        return Response(dict)


class StatisticalDayincrementView(APIView):
    permission_classes = [IsAdminUser]

    def get(self, request):
        day_date = timezone.now().replace(hour=0, minute=0, second=0, microsecond=0)
        counts = User.objects.filter(date_joined__gte=day_date).count()
        dict = {
            'count': counts,
            'date': day_date.date()
        }
        return Response(dict)


class StatisticalDayactiveView(APIView):
    permission_classes = [IsAdminUser]

    def get(self, request):
        now_date = timezone.now().replace(hour=0, minute=0, second=0, microsecond=0)
        counts = User.objects.filter(last_login__gte=now_date).count()
        dict = {
            'count': counts,
            'date': now_date.date()
        }
        return Response(dict)


class StatisticalDayordersView(APIView):
    permission_classes = [IsAdminUser]

    def get(self, request):
        new_date = timezone.now().replace(hour=0, minute=0, second=0, microsecond=0)
        counts = User.objects.filter(orders__create_time__gte=new_date).distinct().count()
        dict = {
            'count': counts,
            'date': new_date.date()
        }
        return Response(dict)


class StatisticalMonthincrementView(APIView):
    permission_classes = [IsAdminUser]

    def get(self, request):
        end_date = timezone.now().replace(hour=0, minute=0, second=0, microsecond=0)
        start_date = end_date - timezone.timedelta(days=29)
        now_date = start_date
        list = []
        while now_date <= end_date:
            next_date = now_date + timezone.timedelta(days=1)
            counts = User.objects.filter(date_joined__gte=now_date, date_joined__lt=next_date).count()
            list.append({
                'count': counts,
                'date': now_date.date()
            })
            now_date = next_date

        return Response(list)


class StatisticalGoodsdayviewsView(APIView):
    permission_classes = [IsAdminUser]

    def get(self, request):
        now_day = timezone.now().date()
        good_category = GoodsVisitCount.objects.filter(date=now_day)
        serializer = GoodsdayviewsSerializer(good_category, many=True)
        return Response(serializer.data)
